package com.ibeeking.found.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.regex.Pattern;
import java.io.IOException;
import java.net.*;
import java.util.Enumeration;

/**
 * 测试网络连通性
 *
 * @author donald
 */
public class IpUtils {
    private static Logger log = LoggerFactory.getLogger(IpUtils.class);

    private static final String ANYHOST_VALUE = "0.0.0.0";
    private static final String LOCALHOST_VALUE = "127.0.0.1";
    private static final Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3,5}$");
    private static final String IP_REGEC_PATTERN = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";

    private static volatile InetAddress LOCAL_ADDRESS = null;

    // ---------------------- valid ----------------------

    public static boolean ipV4Check(String text) {
        if (text != null && !text.isEmpty()) {
            // 判断ip地址是否与正则表达式匹配
            if (text.matches(IP_REGEC_PATTERN)) {
                // 返回判断信息
                return true;
            } else {
                // 返回判断信息
                return false;
            }
        }
        return false;
    }
    private static InetAddress toValidAddress(InetAddress address) {
        if (address instanceof Inet6Address) {
            Inet6Address v6Address = (Inet6Address) address;
            if (isPreferIPV6Address()) {
                return normalizeV6Address(v6Address);
            }
        }
        if (isValidV4Address(address)) {
            return address;
        }
        return null;
    }

    private static boolean isPreferIPV6Address() {
        return Boolean.getBoolean("java.net.preferIPv6Addresses");
    }

    /**
     * valid Inet4Address
     *
     * @param address
     * @return
     */
    private static boolean isValidV4Address(InetAddress address) {
        if (address == null || address.isLoopbackAddress()) {
            return false;
        }
        String name = address.getHostAddress();
        boolean result = (name != null
                && IP_PATTERN.matcher(name).matches()
                && !ANYHOST_VALUE.equals(name)
                && !LOCALHOST_VALUE.equals(name));
        return result;
    }
    /**
     * normalize the ipv6 Address, convert scope name to scope id.
     * e.g.
     * convert
     * fe80:0:0:0:894:aeec:f37d:23e1%en0
     * to
     * fe80:0:0:0:894:aeec:f37d:23e1%5
     * <p>
     * The %5 after ipv6 address is called scope id.
     * see java doc of {@link Inet6Address} for more details.
     *
     * @param address the input address
     * @return the normalized address, with scope id converted to int
     */
    private static InetAddress normalizeV6Address(Inet6Address address) {
        String addr = address.getHostAddress();
        int i = addr.lastIndexOf('%');
        if (i > 0) {
            try {
                return InetAddress.getByName(addr.substring(0, i) + '%' + address.getScopeId());
            } catch (UnknownHostException e) {
                // ignore
                log.debug("Unknown IPV6 address: ", e);
            }
        }
        return address;
    }

    /**
     * 测试本地能否ping ip
     *
     * @param ip
     * @return
     */
    public static boolean isReachIp(String ip) {
        boolean isReach = false;
        try {
            InetAddress address = InetAddress.getByName(ip);// ping this IP

            if (address instanceof java.net.Inet4Address) {
                log.info(ip + " is ipv4 address");
            } else if (address instanceof java.net.Inet6Address) {
                log.info(ip + " is ipv6 address");
            } else {
                log.info(ip + " is unrecongized");
            }
            if (address.isReachable(5000)) {
                isReach = true;
                log.info("SUCCESS - ping " + ip
                        + " with no interface specified");
            } else {
                isReach = false;
                log.info("FAILURE - ping " + ip
                        + " with no interface specified");
            }
        } catch (Exception e) {
            log.error("error occurs:" + e.getMessage());
        }
        return isReach;
    }
    // ---------------------- find ip ----------------------


    private static InetAddress getLocalAddress0() {
        InetAddress localAddress = null;
        try {
            localAddress = InetAddress.getLocalHost();
            InetAddress addressItem = toValidAddress(localAddress);
            if (addressItem != null) {
                return addressItem;
            }
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
        }

        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            if (null == interfaces) {
                return localAddress;
            }
            while (interfaces.hasMoreElements()) {
                try {
                    NetworkInterface network = interfaces.nextElement();
                    if (network.isLoopback() || network.isVirtual() || !network.isUp()) {
                        continue;
                    }
                    Enumeration<InetAddress> addresses = network.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        try {
                            InetAddress addressItem = toValidAddress(addresses.nextElement());
                            if (addressItem != null) {
                                try {
                                    if(addressItem.isReachable(100)){
                                        return addressItem;
                                    }
                                } catch (IOException e) {
                                    // ignore
                                }
                            }
                        } catch (Throwable e) {
                            log.error(e.getMessage(), e);
                        }
                    }
                } catch (Throwable e) {
                    log.error(e.getMessage(), e);
                }
            }
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
        }
        return localAddress;
    }


    // ---------------------- tool ----------------------

    /**
     * Find first valid IP from local network card
     *
     * @return first valid local IP
     */
    public static InetAddress getLocalAddress() {
        if (LOCAL_ADDRESS != null) {
            return LOCAL_ADDRESS;
        }
        InetAddress localAddress = getLocalAddress0();
        LOCAL_ADDRESS = localAddress;
        return localAddress;
    }

    /**
     * get ip address
     *
     * @return String
     */
    public static String getIp(){
        return getLocalAddress().getHostAddress();
    }

    /**
     * get ip:port
     *
     * @param port
     * @return String
     */
    public static String getIpPort(int port){
        String ip = getIp();
        return getIpPort(ip, port);
    }

    public static String getIpPort(String ip, int port){
        if (ip==null) {
            return null;
        }
        return ip.concat(":").concat(String.valueOf(port));
    }

    public static Object[] parseIpPort(String address){
        String[] array = address.split(":");

        String host = array[0];
        int port = Integer.parseInt(array[1]);

        return new Object[]{host, port};
    }


    /**
     * 测试本地所有的网卡地址都能ping通 ip
     *
     * @param ip
     * @return
     */
    public static boolean isReachNetworkInterfaces(String ip) {
        boolean isReach = false;
        try {
            InetAddress address = InetAddress.getByName(ip);// ping this IP

            if (address instanceof java.net.Inet4Address) {
                log.info(ip + " is ipv4 address");
            } else if (address instanceof java.net.Inet6Address) {
                log.info(ip + " is ipv6 address");
            } else {
                log.info(ip + " is unrecongized");
            }
            if (address.isReachable(5000)) {
                isReach = true;
                log.info("SUCCESS - ping " + ip
                        + " with no interface specified");
            } else {
                isReach = false;
                log.info("FAILURE - ping " + ip
                        + " with no interface specified");
            }
            if (isReach) {
                log.info("-------Trying different interfaces--------");
                Enumeration<NetworkInterface> netInterfaces = NetworkInterface
                        .getNetworkInterfaces();
                while (netInterfaces.hasMoreElements()) {
                    NetworkInterface ni = netInterfaces.nextElement();
                    log.info("Checking interface, DisplayName:"
                            + ni.getDisplayName() + ", Name:" + ni.getName());
                    if (address.isReachable(ni, 0, 5000)) {
                        isReach = true;
                        log.info("SUCCESS - ping " + ip);
                    } else {
                        isReach = false;
                        log.info("FAILURE - ping " + ip);
                    }
                    Enumeration<InetAddress> ips = ni.getInetAddresses();
                    while (ips.hasMoreElements()) {
                        log.info("IP: " + ips.nextElement().getHostAddress());
                    }
                    log.info("-----------------check now NetworkInterface is done--------------------------");
                }
            }
        } catch (Exception e) {
            log.error("error occurs:" + e.getMessage());
        }
        return isReach;
    }

    /**
     * 获取能与远程主机指定端口建立连接的本机ip地址
     *
     * @param remoteAddr
     * @param port
     * @return
     */
    public static String getReachableIP(InetAddress remoteAddr, int port) {
        String retIP = null;
        Enumeration<NetworkInterface> netInterfaces;
        try {
            netInterfaces = NetworkInterface.getNetworkInterfaces();
            while (netInterfaces.hasMoreElements()) {
                NetworkInterface ni = netInterfaces.nextElement();
                Enumeration<InetAddress> localAddrs = ni.getInetAddresses();
                while (localAddrs.hasMoreElements()) {
                    InetAddress localAddr = localAddrs.nextElement();
                    if (isReachable(localAddr, remoteAddr, port, 5000)) {
                        retIP = localAddr.getHostAddress();
                        break;
                    }
                }
            }
        } catch (SocketException e) {
            log.error("Error occurred while listing all the local network addresses:"
                    + e.getMessage());
        }
        if (retIP == null) {
            log.info("NULL reachable local IP is found!");
        } else {
            log.info("Reachable local IP is found, it is " + retIP);
        }
        return retIP;
    }

    /**
     * 获取能与远程主机指定端口建立连接的本机ip地址
     *
     * @param remoteIp
     * @param port
     * @return
     */
    public static String getReachableIP(String remoteIp, int port) {
        String retIP = null;
        InetAddress remoteAddr = null;
        Enumeration<NetworkInterface> netInterfaces;
        try {
            remoteAddr = InetAddress.getByName(remoteIp);
            netInterfaces = NetworkInterface.getNetworkInterfaces();
            while (netInterfaces.hasMoreElements()) {
                NetworkInterface ni = netInterfaces.nextElement();
                Enumeration<InetAddress> localAddrs = ni.getInetAddresses();
                while (localAddrs.hasMoreElements()) {
                    InetAddress localAddr = localAddrs.nextElement();
                    if (isReachable(localAddr, remoteAddr, port, 5000)) {
                        retIP = localAddr.getHostAddress();
                        break;
                    }
                }
            }
        } catch (UnknownHostException e) {
            log.error("Error occurred while listing all the local network addresses:" + e.getMessage());
        } catch (SocketException e) {
            log.error("Error occurred while listing all the local network addresses:" + e.getMessage());
        }
        if (retIP == null) {
            log.info("NULL reachable local IP is found!");
        } else {
            log.info("Reachable local IP is found, it is " + retIP);
        }
        return retIP;
    }

    /**
     * 测试localInetAddr能否与远程的主机指定端口建立连接相连
     *
     * @param localInetAddr
     * @param remoteInetAddr
     * @param port
     * @param timeout
     * @return
     */
    public static boolean isReachable(InetAddress localInetAddr,
                               InetAddress remoteInetAddr, int port, int timeout) {
        boolean isReachable = false;
        Socket socket = null;
        try {
            socket = new Socket();
// 端口号设置为 0 表示在本地挑选一个可用端口进行连接
            SocketAddress localSocketAddr = new InetSocketAddress(
                    localInetAddr, 0);
            socket.bind(localSocketAddr);
            InetSocketAddress endpointSocketAddr = new InetSocketAddress(
                    remoteInetAddr, port);
            socket.connect(endpointSocketAddr, timeout);
            log.info("SUCCESS - connection established! Local: "
                    + localInetAddr.getHostAddress() + " remote: "
                    + remoteInetAddr.getHostAddress() + " port" + port);
            isReachable = true;
        } catch (IOException e) {
            log.error("FAILRE - CAN not connect! Local: "
                    + localInetAddr.getHostAddress() + " remote: "
                    + remoteInetAddr.getHostAddress() + " port" + port);
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    log.error("Error occurred while closing socket:"
                            + e.getMessage());
                }
            }
        }
        return isReachable;
    }

    /**
     * 测试localIp能否与远程的主机指定端口建立连接相连
     *
     * @param localIp
     * @param remoteIp
     * @param port
     * @param timeout
     * @return
     */
    public static boolean isReachable(String localIp, String remoteIp,
                               int port, int timeout) {
        boolean isReachable = false;
        Socket socket = null;
        InetAddress localInetAddr = null;
        InetAddress remoteInetAddr = null;
        try {
            localInetAddr = InetAddress.getByName(localIp);
            remoteInetAddr = InetAddress.getByName(remoteIp);
            socket = new Socket();
// 端口号设置为 0 表示在本地挑选一个可用端口进行连接
            SocketAddress localSocketAddr = new InetSocketAddress(
                    localInetAddr, 0);
            socket.bind(localSocketAddr);
            InetSocketAddress endpointSocketAddr = new InetSocketAddress(
                    remoteInetAddr, port);
            socket.connect(endpointSocketAddr, timeout);
            log.info("SUCCESS - connection established! Local: "
                    + localInetAddr.getHostAddress() + " remote: "
                    + remoteInetAddr.getHostAddress() + " port" + port);
            isReachable = true;
        } catch (IOException e) {
            log.error("FAILRE - CAN not connect! Local: "
                    + localInetAddr.getHostAddress() + " remote: "
                    + remoteInetAddr.getHostAddress() + " port" + port);
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    log.error("Error occurred while closing socket:"
                            + e.getMessage());
                }
            }
        }
        return isReachable;
    }

    public static void main(String[] args) {
        if(IpUtils.ipV4Check("189.100.1.151")){
            log.info("=======ip：" + "47.100.119.151 check ok");
        }else {
            log.info("=======ip：" + "47.100.119.151  check error");
        }
//        if (IpUtils.isReachIp("47.100.119.151")) {
//            log.info("=======本机可以ping通ip：" + "47.100.119.151");
//        } else {
//            log.info("=======本机ping不通ip：" + "47.100.119.151");
//        }
//        if (IpUtils.isReachNetworkInterfaces("47.100.119.151")) {
//            log.info("=======本机所有网卡可以ping通ip：" + "47.100.119.151");
//        } else {
//            log.info("=======本机所有网卡ping不通ip：" + "47.100.119.151");
//        }
//        String localIp = IpUtils.getReachableIP("47.100.119.151", 6020);
//        if (!StringUtils.isBlank(localIp)) {
//            log.info("=======本机可以与ip：" + "47.100.119.151" + ",port:" + 6020 + "建立连接的IP：" + localIp);
//        } else {
//            log.info("=======本机不能与ip：" + "47.100.119.151" + ",port:" + 6020 + "建立连接的IP");
//        }
    }

}